# Create your views here.
from django.template import loader,Context
from django.http import HttpResponse
from blog.models import BlogPost 

def archive(request):
	posts = BlogPost.objects.all()
	t = loader.get_template("archive.html")
	c = Context({'posts':posts})
	return HttpResponse(t.render(c))


from django import forms
from django.shortcuts import render,render_to_response
from blog.models import User


class UserForm(forms.Form):
    username = forms.CharField()
    headImg = forms.FileField()

def register(request):
    
    if request.method == "POST":
        
        uf = UserForm(request.POST,request.FILES)
        if uf.is_valid():
        	
            username = uf.cleaned_data['username']
            headImg = uf.cleaned_data['headImg']
            
            print(username)
            print(headImg)

            handle_uploaded_file(headImg)


            user = User()
            user.username = username
            user.headImg = headImg
            user.save()
            return HttpResponse('upload ok!')
    else:
        uf = UserForm()
    return render_to_response('register.html',{'uf':uf})

import urllib2
import urllib
import json

# def register(request):
    
#     if request.method == "POST":
                
#             #username = request.POST['username']
#             data = request.POST['data']
#             print data
#             username = 'lll'
#             headImg = request.FILES['file']
            
#             print(username)
#             print(headImg)

#             handle_uploaded_file(headImg)

#             response_data = {}
#             response_data['code'] = '10000'
#             response_data['msg'] = 'success'
#             return HttpResponse(json.dumps(response_data), content_type="application/json")

#             #return HttpResponse(encodedjson)
#     else:
#         uf = UserForm()
#     return render_to_response('register.html',{'uf':uf})


import urllib
import os

def handle_uploaded_file(f):

    picpath = 'D:\\ImageDownload6\\' 
  
    if not os.path.exists(picpath):
        os.makedirs(picpath)   

    name = "%s" % f.name
    destination = open('%s/%s' % (picpath, name), 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()